package com.itboye.eweilisten.me.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.eweilisten.R;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.model.GoPayBean;
import com.itboye.eweilisten.model.WeiXinPayBean;
import com.itboye.eweilisten.presenter.UserPresenter;
import com.itboye.eweilisten.util.MyGongJv;
import com.itboye.eweilisten.util.alipay.OrderInfoUtil2_0;
import com.itboye.eweilisten.util.alipay.PayResult;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.widget.IsStringSPUtils;
import com.itboye.eweilisten.volley.ResultEntity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 支付页面
 */
public class ActivityShopPlay extends BaseActivity implements Observer {
    private ImageView img_zhifubao_check;
    private ImageView img_weixin_check;
    RelativeLayout pay_zfb, pay_weixin;
    private int payType = 1;//默认为1支付宝
    boolean isZFB = true, isWX;
    private TextView queren;
    private TextView tvTitle, tv_time;
    private ImageView back;
    public static String GOUWUINEXIT = "gouwu.end.exit";// 购物结束
    GoPayBean bean;
    UserPresenter presenter;
    private IWXAPI api;
    WeiXinPayBean weixinBean;
    String price;
    String sku_pkid;
    String idcode, note;

    String type, order_code;//type 标记是重新支付还是立即支付    order_code  重新支付的order_code

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_go_play);
        init();
        api = WXAPIFactory.createWXAPI(this, Const.APP_ID, false);
        api.registerApp(Const.APP_ID);
        price = getIntent().getStringExtra("price");
        sku_pkid = getIntent().getStringExtra("sku_pkid");
        idcode = getIntent().getStringExtra("idcode");
        note = getIntent().getStringExtra("note");
        type = getIntent().getStringExtra("type");
        order_code = getIntent().getStringExtra("order_code");
        tv_time.setText(price + "元");
        presenter = new UserPresenter(this);
        bean = new GoPayBean();
        weixinBean = new WeiXinPayBean();

        //购物结束的广播
        IntentFilter filter = new IntentFilter(GOUWUINEXIT);
        registerReceiver(gouwuReceiver, filter);
    }

    BroadcastReceiver gouwuReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(gouwuReceiver);
    }

    public void init() {
        tvTitle.setText(getString(R.string.zhifufangshi));
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.queren:
                switch (payType) {
                    case 1:
                        isZFB = true;
                        isWX = false;
                        zhifubaoPay();
                        break;
                    case 2:
                        isZFB = false;
                        isWX = true;
                        weixinPay();
                        break;
                }
                break;
            case R.id.pay_zfb:
                img_zhifubao_check.setBackgroundResource(R.drawable.pay_type_selected);
//                setPayTypeSelected(1);
                break;
//            case R.id.pay_weixin:
//                setPayTypeSelected(2);
//                break;
        }
    }

    /**
     * 支付宝支付
     */
    private void zhifubaoPay() {
        showProgressDialog("请稍后", true);
        Log.d("onPlipayonPlipay", IsStringSPUtils.getSid());
        if (type.equals("chongxin")) {//重新支付
            presenter.chongxinPlipay(IsStringSPUtils.getSid(), IsStringSPUtils.IsUid(), order_code);
        } else {
            presenter.onPlipay(idcode, IsStringSPUtils.getSid(), IsStringSPUtils.IsUid(), sku_pkid, note);
        }

    }

    /**
     * 微信支付
     */
    private void weixinPay() {
        showProgressDialog("请稍后", true);
        Log.d("onPlipayonPlipay", IsStringSPUtils.getSid());
        if (type.equals("chongxin")) {//重新支付
            presenter.chongxinPlipay(IsStringSPUtils.getSid(), IsStringSPUtils.IsUid(), order_code);
        } else {
            presenter.onPlipay(idcode, IsStringSPUtils.getSid(), IsStringSPUtils.IsUid(), sku_pkid, null);
        }
    }

    /**
     * @param type 支付方式的选中状态
     *             1、支付宝
     *             2、钱包
     *             3、微信
     */
    public void setPayTypeSelected(int type) {
        clearAllSelected();
        switch (type) {
            case 1:
                img_zhifubao_check.setBackgroundResource(R.drawable.pay_type_selected);
                break;
            case 2:
                img_weixin_check.setBackgroundResource(R.drawable.pay_type_selected);
                break;
        }
        payType = type;
    }

    public void clearAllSelected() {
        img_zhifubao_check.setBackgroundResource(R.drawable.pay_type_unselected);
        img_weixin_check.setBackgroundResource(R.drawable.pay_type_unselected);
    }

    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (entity.getCode().equals("1111")) {
                Intent intent = new Intent(MyApplication.instance, LoginActivity.class);
                startActivity(intent);
                return;
            }
            //立即支付
            if (entity.getEventType() == presenter.Plilay_success) {
                bean = (GoPayBean) entity.getData();

                if (isZFB) {
                    System.out.print("isZFB");
                    zfb(bean);
                } else if (isWX) {
                    presenter.onWeiXinPay(bean.getPay_code(),IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
                }
            }
            if (entity.getEventType() == presenter.Plilay_fail) {
                MAlert.alert(entity.getData());
            }
            //重新支付
            if (entity.getEventType() == presenter.chongxin_Plilay_success) {
                bean = (GoPayBean) entity.getData();

                if (isZFB) {
                    System.out.print("isZFB");
                    zfb(bean);
                } else if (isWX) {
                    presenter.onWeiXinPay(bean.getPay_code(),IsStringSPUtils.IsUid(),IsStringSPUtils.getSid());
                }
            }
            if (entity.getEventType() == presenter.chongxin_Plilay_fail) {
                MAlert.alert(entity.getData());
            }
            if (entity.getEventType() == presenter.weixin_pay_success) {
                weixinBean = (WeiXinPayBean) entity.getData();

                PayReq req = new PayReq();
                req.appId = Const.APP_ID;
                req.partnerId = weixinBean.getPartnerid();
                req.prepayId = weixinBean.getPrepayid();
                req.nonceStr = weixinBean.getNoncestr();
                req.timeStamp = weixinBean.getTimestamp();
                req.packageValue = "Sign=WXPay";
                req.sign = weixinBean.getSign();
                boolean is = api.sendReq(req);
                if (is) {
//                    ByAlert.alert("已调其成功");
//                    finish();
                } else {
                    MAlert.alert("调起微信支付失败");
                }
            }
            if (entity.getEventType() == presenter.weixin_pay_fail) {
                MAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    private static final int SDK_PAY_FLAG = 1;

    /**
     * 支付宝
     */
    private void zfb(GoPayBean bean) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        String money = bean.getPay_money();
        double m = Double.parseDouble(money) / 100;
        String content = bean.getPay_code();
        String code = bean.getPay_code();
        String time = bean.getCreate_time();
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(Const.APPID, m + "", content, code, time);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, Const.RSA_PRIVATE);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ActivityShopPlay.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ActivityShopPlay.this, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                        // 发送广播通知LoginActivity结束
                        Intent intent1 = new Intent(GOUWUINEXIT);
                        sendBroadcast(intent1);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。(注：如果没有安装支付宝客户端选择其他支付会出现异常，所以没有安装支付宝客户端的时候结束掉页面)
                        if (MyGongJv.isAvilible(ActivityShopPlay.this, "com.eg.android.AlipayGphone")) {

                            Toast.makeText(ActivityShopPlay.this, "支付失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ActivityShopPlay.this, "支付失败,检测到手机没有安装支付宝，请到订单中支付", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        try {
                            closeProgressDialog();
                        } catch (Exception e) {
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
}
